package com.proactive.webapp.controller;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.proactive.webapp.dao.ManagerDAO;
import com.proactive.webapp.dao.MenuDAO;
import com.proactive.webapp.entity.Manager;
import com.proactive.webapp.entity.Member;
import com.proactive.webapp.entity.Menu;
import com.proactive.webapp.util.MenuUtil;
import com.proactive.webapp.util.SecurityMD5;

@Controller
public class ManagerController {
	ApplicationContext context =  new ClassPathXmlApplicationContext("spring-module.xml");
	
	@RequestMapping(value = "/management/login", method = RequestMethod.GET)
	public ModelAndView getResourceList(HttpSession session) {
		ModelAndView model = new ModelAndView();
		Manager loginManager = (Manager)session.getAttribute("loginManager");
		if(loginManager == null){
			if(session.getAttribute("errorMsg") != null){
				String errorMsg = session.getAttribute("errorMsg").toString();
				session.removeAttribute("errorMsg");
				model.addObject("errorMsg", errorMsg);
			}
			
			model.setViewName("management/login");
		}
		else
			model.setViewName("redirect:/management/manageCardTemplate");
		return model;
	}
	
	@RequestMapping(value = "/management/checkLogin", method = RequestMethod.POST)
	public ModelAndView checkLogin(@ModelAttribute Manager manager, HttpSession session, HttpServletRequest request) throws IOException {
		ModelAndView model = new ModelAndView();
		SecurityMD5 securityMD5 = new SecurityMD5();
		ManagerDAO memberDAO = (ManagerDAO)context.getBean("managerDAO");
		try {
			manager.setPassword(securityMD5.encryptWords(manager.getPassword()));
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		manager = memberDAO.checkLogin(manager);
		if(manager.isLogin()){
			session.setAttribute("loginManager", manager);
			model.setViewName("redirect:/management/login");
			
		}
		else{
			session.setAttribute("errorMsg", "登入失敗");
			model.setViewName("redirect:/management/login");
			
		}
		return model;
	}
	
	@RequestMapping(value = "/management/logout", method = RequestMethod.GET)
	public ModelAndView logout(HttpServletRequest request, HttpSession session) {
		ModelAndView model = new ModelAndView("redirect:/management/login");
		session.removeAttribute("loginManager");
		return model;
	}
}
